/*
 * 描述 数据源配置接口
 * Create by cy on 2025/06/16
 * */

const express = require("express");
const router = express.Router();
const db = require("../../db");

router.get("/list", (req, res) => {
  let s = `SELECT * from express.sql_templates`;

  db.query(s, function (error, result) {
    if (error) throw error;
    res.json({
      data: result,
    });
  });
});
//新增接口
router.post("/create", (req, res) => {
  const {
    template_name,
    template_module_id,
    template_content,
    description,
    created_by,
  } = req.body;
  const sql = `INSERT INTO sql_templates 
    (template_name, template_module_id, template_content, description, created_by) 
    VALUES (?, ?, ?, ?)`;

  db.query(
    sql,
    [
      template_name,
      template_module_id,
      template_content,
      description,
      created_by,
    ],
    (error, result) => {
      if (error) {
        res.status(500).json({ error: error.message });
        return;
      }
      res.json({ id: result.insertId });
    }
  );
});
//修改接口
router.post("/update", (req, res) => {
  const {
    id,
    template_name,
    template_module_id,
    template_content,
    description,
    created_by,
  } = req.body;
  const sql = `UPDATE sql_templates SET template_name=?, template_module_id=?, template_content=?, description=?, created_by=? WHERE id=?`;
  db.query(
    sql,
    [
      template_name,
      template_module_id,
      template_content,
      description,
      created_by,
      id,
    ],
    (error, result) => {
      if (error) throw error;
      res.json({});
    }
  );
});
//删除接口
router.post("/delete", (req, res) => {
  const { id } = req.body;
  const sql = `DELETE FROM sql_templates WHERE id=?`;
  db.query(sql, [id], (error, result) => {
    if (error) throw error;
    res.json({});
  });
});
module.exports = router;
